import paddle
import paddle.nn as nn
import paddle.optimizer as optim
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 读取CSV文件
data = pd.read_csv('homework12/用户行为分析.csv')

# 假设CSV文件中有特征列和标签列，这里需要根据实际情况调整
# 例如：特征列为除了最后一列的所有列，标签列为最后一列
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values

# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 将数据转换为飞桨张量
X_train = paddle.to_tensor(X_train, dtype='float32')
X_test = paddle.to_tensor(X_test, dtype='float32')
y_train = paddle.to_tensor(y_train, dtype='float32')  # 根据实际情况，标签可能是int或其他类型
y_test = paddle.to_tensor(y_test, dtype='float32')

# 定义简单的神经网络模型
class SimpleNN(nn.Layer):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

# 初始化模型参数
input_dim = X_train.shape[1]
hidden_dim = 64  # 可以调整隐藏层神经元数量
output_dim = 1 if y_train.dtype == 'float32' else len(set(y_train.numpy()))  # 根据标签类型调整输出维度

model = SimpleNN(input_dim, hidden_dim, output_dim)

# 定义损失函数和优化器
criterion = nn.MSELoss() if y_train.dtype == 'float32' else nn.CrossEntropyLoss()
optimizer = optim.Adam(parameters=model.parameters(), learning_rate=0.001)

# 训练模型
num_epochs = 100  # 可以调整训练轮数
for epoch in range(num_epochs):
    model.train()
    optimizer.clear_grad()
    outputs = model(X_train)
    loss = criterion(outputs, y_train)
    loss.backward()
    optimizer.step()

    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.numpy()[0]}')

# 测试模型
model.eval()
with paddle.no_grad():
    if y_test.dtype == 'float32':
        predictions = model(X_test).numpy()
        # 计算回归问题的评估指标，如MSE等（这里仅展示预测结果）
        print("Predictions:", predictions)
    else:
        predictions = model(X_test).argmax(axis=1).numpy()  # 如果是分类问题，取概率最大的类别
        # 计算分类问题的评估指标，如准确率等（这里仅展示预测结果）
        print("Predictions:", predictions)```